;(function(undefined) {
    "use strict"
    var _global;
    function result(args,fn){
        var argsArr = Array.prototype.slice.call(args);
        if(argsArr.length > 0){
            return argsArr.reduce(fn);
        } else {
            return 0;
        }
    }
    var deviceList = {
        columnsInit:function(){
            return  [
            	{
                    field: 'deviceCode',
                    title: '设备编码',
                    valign:"middle",
                    sortable :true
                },
                {
                    field: 'deviceName',
                    title: '设备名称',
                    valign:"middle"
                },
                {
                    field: 'dptlName',
                    title: '服务协议',
                    valign:"middle",
                    sortable :true
                },
                {
                    field: 'rowSort',
                    title: '排序号',
                    valign:'middle',
	            	width: 80,
	            	sortable : true
                },
                {
                    field: 'status',
                    title: '状态',
                    align:"center",
                    valign:"middle",
                    width: 120,
                    formatter: function (value, row, index) {
                        if(value == '1'){
                            return [
                                '<span class="sys-type-bg pro-status-green">正常</span>'
                            ];
                        }
                        return [
                            '<span class="sys-type-bg pro-status-red">停用</span>'
                        ];
                    }
                },
                {
                    field: 'optionDel',
                    checkbox: true
                },
                {
                field: 'option',
                title: '操作',
                width: 80,
                align: 'center',
                formatter: function (value, row, index) {
                    return [
                        '<div class="opt-dropdown tb-opt-div"><a class="tb-opt-icon" href="javascript:void(0)">操作 <i class="glyphicon glyphicon-triangle-bottom"></i></a>',
                        '<ul class="opt-dropdown-menu opt-dropdown-menu-bottom">',
                        '<li><a href="javascript:updateDevice(\''+row.id+'\')" title="编辑">',
                        '<i class="glyphicon glyphicon-pencil"></i><em> 编辑</em></a></li>'
                    ].join('');
                }
            }]
        },
        gridInit:function(columns){
            return $("#deviceTable").bootstrapTable({
                method:"post",
                contentType:"application/x-www-form-urlencoded",
                columns: columns,
                undefinedText:'-',
                striped: 'true',
                classes: 'table table-hover qxttable',
                pagination: 'true',
                clickToSelect: true,
                singleSelect:false,
                sidePagination: "server",
                queryParamsType : "page",
                sortSide:'client',
                sortable:true,
                pageNumber: 1,
                pageSize:10,
                idField:'id',
                silentSort: true,
                pageList: [
                	10, 20, 50, 100
                ],
                onClickRow:function(row, $element,field){
                     $("#deviceTable").bootstrapTable("uncheckAll");
                },
                queryParams: function queryParams(params) {
	                var args={};
	                var catalogId = $("#catalogId").val();
	                var deviceCode = $("#deviceCode").val();
	                var deviceName = $("#deviceName").val();
	                if(catalogId!=="0"){
	                	args.c_catalogId_1 = catalogId;
	                }
	                if(deviceCode!==""){
	                	args.c_deviceCode_7 = deviceCode;
	                }
	                if(deviceName!==""){
	                	args.c_deviceName_7 = deviceName;
	                }
	                args.page=params.pageNumber-1; //    params.pageNumber
	                args.pageSize=params.pageSize;     //params.pageSize
	                args.isPage=1;
	                var paramStr=JSON.stringify(args);
	                var param = {
	                    params:paramStr
	                };
	                return param;
	            },
                onPostBody:function () {
                    $(".opt-dropdown").each(function(index,data){
                        var _this = this;
                        $(this).hover(function(){
                            $(_this).find(".opt-dropdown-menu").show();
                        },function(){
                            $(_this).find(".opt-dropdown-menu").hide();
                        })
                    });
                }
            })
        },
        refresh: function () {
        	$("#deviceTable").bootstrapTable('refresh',{url:$$.restIotServerUrl+'/bootstrap/basegrid/IotDeviceBusiness/list'});
        }
    };
    // 将插件对象暴露给全局对象
    _global = (function(){ return this || (0, eval)('this'); }());
    if (typeof module !== "undefined" && module.exports) {
        module.exports = deviceList;
    } else if (typeof define === "function" && define.amd) {
        define(function(){return deviceList;});
    } else {
        !('plugin' in _global) && (_global.deviceList = deviceList);
    }
}());

/**
 * 类别树刷新
 * @returns
 */
function refreshTree(){
    $("#treeParent").empty();
    $("#treeParent").append('<div id="authorityTable"></div>');
    initTree();
}

/**
 * 初始化类别树
 * @returns
 */
function initTree() {
    $$.ajax({
        url: "/rest/IotDeviceCatalogBusiness/listAllSort",
        suiteCode:"iot",
        async: false,
        data: {
            menuCode: ""
        },
        success: function (data) {
        	createDeptTree(data);
        }
    });
}

/**
 * 创建类别树
 * @param sourceData
 * @returns
 */
function createDeptTree(sourceData){
	var source = {
        dataType: "json",
        dataFields: [{
            name: "stockName",
            type: "string",
        }, {
            name: "DataSourceID",
            type: "string",
        }, {
            name: 'children',
            type: 'array'
        }, {
            name: 'expanded',
            type: 'bool'
        }],
        hierarchy: {
            root: 'children'
        },
        id: 'DataSourceID',
        localData: sourceData
    };
    var dataAdapter = new $.jqx.dataAdapter(source);
    var iHeight = $("#rightCont").height() - 30;
    // create Tree Grid
    $("#authorityTable").jqxTreeGrid({
        source: dataAdapter,
        width: '100%',
        altRows: true,
        selectionMode: "singleRow",
        height: iHeight,
        theme: 'bootstrap',
        showToolbar: false,
        enableHover: true,
        columns: [{
            text: "设备分类",
            align: "center",
            dataField: "stockName",
            cellsRenderer: function (row, column, value, rowData) {
                var container ="";
                if(rowData.DataSourceID==-1 || rowData.DataSourceID==0){
                    container = '<span style="width: 100%; height: 100%;">';
                    var data = '<span class="tree-item-text" title=" ' + value + ' ">' + value + '</span>'
                    var option = '<span class="rt tree-item-opt hidden">' +
                        '<a href="javascript:void(0)"><i class="glyphicon glyphicon-plus" onclick="addClassify(event,\'' + rowData.DataSourceID + '\')"></i></a>' +
                        '</span>';
                    container += data;
                    container += option;
                    container += "</span>";
                }else{
                    container = '<span style="width: 100%; height: 100%;">';
                    var data = '<span class="tree-item-text" title=" ' + value + ' ">' + value + '</span>'
                    var option = '<span class="rt tree-item-opt hidden">' +
                        '<a href="javascript:void(0)"><i class="glyphicon glyphicon-plus" onclick="addClassify(event,\'' + rowData.DataSourceID + '\')"></i></a>' +
                        '<a href="javascript:void(0)"><i class="glyphicon glyphicon-pencil" onclick="editClassify(event,\'' + rowData.DataSourceID + '\')"></i></a>' +
                        '<a href="javascript:void(0)"><i class="glyphicon glyphicon-trash" onclick="delClassify(event,\'' + rowData.DataSourceID + '\')"></i></a></span>';
                    container += data;
                    container += option;
                    container += "</span>";
                }
                return container;
            },
        }],
        ready:function () {
            classifyOpt();
        }
    });

    //点击左边tree,右侧table refresh
    $("#authorityTable").on('rowSelect', function (event) {
    	var args = event.args;
    	$("#catalogId").val(args.row.DataSourceID);
    	deviceList.refresh();
    });
    var selectCatalogId = $("#catalogId").val();
    if(selectCatalogId!==""){
    	$("#authorityTable").jqxTreeGrid('selectRow', selectCatalogId);
    }
}

/**
 * 树操作按钮
 * @returns
 */
function classifyOpt() {
    $("#authorityTable").on("mouseover mouseout","tr",function(event){
        console.log(event.type);
        if(event.type == 'mouseover'){
            $(this).find('.rt').removeClass('hidden');
        }else{
            $(this).find('.rt').addClass('hidden');
        }
    });
}

//新建分类弹出框
function addClassify(e, pid) {
    e = e || window.event;
    var openWin;
    layer.open({
        move: false,
        type: 2,
        title: '新建分类',
        area: ['800px', '430px'],
        content: 'device_catalog_add.html?',
        btn: ['确定', '取消'],
        btnAlign: 'c',
        success: function (layero, index) {
            openWin = window[layero.find('iframe')[0]['name']];
            openWin.addLoad(pid);
        },
        yes: function (index, layero) {
            var ret = openWin.submitForm();
            if (ret) {
                layer.close(index);
                refreshTree();
            }
        }, cancel: function (index) {
            layer.close(index);
        }
    });
    e.stopPropagation();
}

//编辑分类弹出框
function editClassify(e, id) {
    e = e || window.event;
    var openWin;
    layer.open({
        move: false,
        type: 2,
        title: '修改分类',
        area: ['800px', '430px'],
        content: 'device_catalog_update.html',
        btn: ['确定', '取消'],
        btnAlign: 'c',
        success: function (layero, index) {
            openWin = window[layero.find('iframe')[0]['name']];
            openWin.updateLoad(id);
        },
        yes: function (index, layero) {
            var ret = openWin.submitForm();
            if (ret) {
                layer.close(index);
                refreshTree();
            }
        }, cancel: function (index) {
            layer.close(index);
        }
    });
    e.stopPropagation();
}

//删除分类弹出框
function delClassify(e, data) {
    e = e || window.event;
    layer.confirm(
		'确定要删除分类吗？',
        {icon: 3, title: '提示', area: '300px', btnAlign: 'c'}, 
        function (index) {
            $$.ajax({
                url: "/rest/IotDeviceCatalogBusiness/remove",
                suiteCode:'iot',
                data: {
                    id: data
                },
                success: function () {
                    layer.close(index);
                    refreshTree();
                }
            });
        }
    );
    e.stopPropagation();
}

/**
 * 新增
 */
function addDevice() {
	var catalogId = $("#catalogId").val();
	if(catalogId==="0"){
		catalogId = "-1";
	}
	openOperateWindow("device_add.html","add","",catalogId);
}

/**
 * 修改
 */
function updateDevice(id) {
	var catalogId = $("#catalogId").val();
	if(catalogId==="0"){
		catalogId = "-1";
	}
    openOperateWindow("device_add.html","update",id,catalogId);
}

/**
 * 打开操作窗口
 */
function openOperateWindow(url,type,id,catalogId){
	var title = "";
	if(type=="add"){
		title = "新建设备";
	}else{
		title = "修改设备";
	}
	var openWin;
    layer.open({
        move: false,
        type: 2,
        resize:false,
        title: title,
        area: ['800px', '500px'],
        content: url,
        btn: ['确定','关闭'],
        btnAlign: 'c',
        success: function (layero, index) {
            openWin = window[layero.find('iframe')[0]['name']];
            openWin.initData(type,id,catalogId);
        },
        yes: function (index, layero) {
            var validFormRes = openWin.submitForm();
            if(validFormRes){
            	layer.close(index);
            	layer.msg(title+"成功！",{time:1000});
            	deviceList.refresh();
            }
        },
        cancel: function (index) {
            layer.close(index);
        }
    });
}

/**
 * 批量删除数据
 */
function batchDeleteData(){
	var len = $("#deviceTable input:checked").length;
    if (len == 0) {
        layer.msg('请选择数据！',{time:1000});
    } else {
        layer.confirm('您确定要删除选中数据吗？',{icon: 3, title: '提示', area: '300px', btnAlign: 'c'}, function (index) {
        	var indexLoad = layer.load(2);
			var indexTips = layer.tips('正在努力删除数据，请等待...','#del-btn',{time:30*60*1000});
        	var rowDatas= $("#deviceTable").bootstrapTable('getSelections');
        	var rowIds = [];
        	for (var i = 0; i < rowDatas.length; i++) {
            	rowIds.push(rowDatas[i].id);
        	}
        	layer.close(index);
        	$$.ajax({
            	url: "/rest/IotDeviceBusiness/remove",
            	suiteCode:'iot',
            	data: {
                	id : rowIds.join(',')
            	},
            	success: function(data) {
            		layer.close(indexLoad);
		        	layer.close(indexTips);
            		deviceList.refresh();
            	},
            	serror : function(){
            		layer.close(indexLoad);
		        	layer.close(indexTips);
            	},
            	error: function(){
            		layer.close(indexLoad);
		        	layer.close(indexTips);
            	}
        	});
        });
    }
}

/**
 * 设置分类
 * @returns
 */
function setCatalog(){
	var len = $("#deviceTable input:checked").length;
    if(len == 0) {
        layer.msg('请选择数据！',{time:1000});
    }else{
    	var openWin;
        layer.open({
            move: false,
            type: 2,
            resize:false,
            title: "设置分类",
            area: ['800px', '500px'],
            content: "catalog_select.html",
            btn: ['确定','关闭'],
            btnAlign: 'c',
            success: function (layero, index) {
                openWin = window[layero.find('iframe')[0]['name']];
            },
            yes: function (index, layero) {
                var catalogData = openWin.getSelectCatalogData();
                if(catalogData){
                	layer.close(index);
                	var indexLoad = layer.load(2);
        			var indexTips = layer.tips('正在努力保存数据，请等待...','#setCatalog-btn',{time:30*60*1000});
        			//类别id
                	var selectCatalogId = catalogData.DataSourceID;
                	if(selectCatalogId==="0"){
                		selectCatalogId = "-1";
                	}
                	//移动数据id
                	var rowDatas= $("#deviceTable").bootstrapTable('getSelections');
                	var rowIds = [];
                	for (var i = 0; i < rowDatas.length; i++) {
                    	rowIds.push(rowDatas[i].id);
                	}
                	//保存数据
                	$$.ajax({
                    	url: "/rest/IotDeviceBusiness/setCatalog",
                    	suiteCode:'iot',
                    	data: {
                    		catalogId: selectCatalogId,
                        	ids: rowIds.join(',')
                    	},
                    	success: function(data) {
                    		layer.close(indexLoad);
        		        	layer.close(indexTips);
        		        	layer.tips('数据保存成功！','#setCatalog-btn',{time:1000});
                    		deviceList.refresh();
                    	},
                    	serror : function(){
                    		layer.close(indexLoad);
        		        	layer.close(indexTips);
                    	},
                    	error: function(){
                    		layer.close(indexLoad);
        		        	layer.close(indexTips);
                    	}
                	});
                }
            },
            cancel: function (index) {
                layer.close(index);
            }
        });
    }
}

$(function () {
    $('#deviceCode').focus();
    
  //渲染表格
    var columns = deviceList.columnsInit();
    var table = deviceList.gridInit(columns);
    
    //tree
    initTree();
    
    //重置表单
    $("#searchReset").on("click",function(){
        $('#deviceCode').val('');
        $('#deviceName').val('');
        deviceList.refresh();
    });
    
    //按钮搜索
    $("#serachBtn").on("click",function(){
        deviceList.refresh();
    });
    
    //回车搜索
    $('.entrer-query').bind('keypress',function(e){
        if(e.keyCode == 13){
            deviceList.refresh();
        }
    });
    
    //点击删除按钮信息弹出框
    $("#del-btn").click(function(){
		batchDeleteData();
    });
});